<?php

!defined('IN_SYSTEM') && exit('Access denied');

class managerControlPage extends commonControlPage {

    public function manageModule() {
        $rowset = $_ENV['db']->fetch("SELECT COUNT(uid) as `total` FROM `admincp_member`");
        $total = $rowset['total'];
        unset($rowset);

        $pager = new class_pager();
        $pager->setConfig((int)$_GET['page_no'],$total);
        $pager->setUrl('?app='.APP.'&mod='.MOD.'&page_no=TPT','TPT');

        $this->view->members = (array)$_ENV['db']->fetchAll('SELECT * FROM `admincp_member` ORDER BY `uid` DESC LIMIT '.$pager->getLimit().' OFFSET '.$pager->getOffset());
        $this->view->pager = $pager->output();
        $this->showMainPage('admincp/manager_manage');
    }

    public function addModule() {
        if (POST && AJAX) {
            $fields = array('username','nickname','password','password_confirm','group_id');
            $member = getRequests($fields);

            foreach($fields as $key => $row) {
                if(!$member[$row]) {
                    $this->outputJson(-1,'请补全必填信息',$row);
                }
            }

            if(!$member['password'] || $member['password'] != $member['password_confirm']) {
                $this->outputJson(-1,'请确认密码','password');
            }

            if(!$member['group_id'] || !$_ENV['db']->fetchCol("SELECT gid FROM `admincp_member_group` WHERE `gid` = '{$member['group_id']}'")) {
                $this->outputJson(-1,'用户组选择错误','group_id');
            }

            $detail = getRequests(array('statutory_holiday','job','mobile','tel','tel','address','nplace','education','birthday','school'));

            if ($detail['mobile'] && (!is_numeric($detail['mobile']) || strlen($detail['mobile']) != 11)) {
                $this->outputJson(-2,'手机号码必须是数字且为11位长度','mobile');
            }
            
            $tel_length = strlen($detail['tel']);
            if ($tel_length && (!is_numeric($detail['tel']) || ($tel_length != 11 && $tel_length != 7))) {
                $this->outputJson(-2,'座机号码只能为数字且长度为7或11位，区号和号码之间不用任何符号','tel');
            }

			 if($detail['statutory_holiday'] && !preg_match('/\d{3}/',$detail['statutory_holiday'] )) {
                $this->outputJson(-2,'法定日期必须是0~365之内的纯数字','birthday');
            }
			 if($detail['statutory_holiday'] && (int)$detail['statutory_holiday'] <0 || (int)$detail['statutory_holiday'] >365 ) {
                $this->outputJson(-2,'法定日期必须是0~365之内的纯数字','birthday');
            }

            if($detail['birthday'] && !strtotime($detail['birthday'])) {
                $this->outputJson(-2,'生日格式错误，识别失败。','birthday');
            }

            $member_row = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `username` = '{$member['username']}'");
            if (!empty($member_row)) {
                $this->outputJson(-1,'用户名已存在','username');
            }

            unset($member['password_confirm']);
            $member['password'] = md5($member['password']);

            $_ENV['db']->beginTransaction();
            $_ENV['db']->runSql(getFastInsertSql('admincp_member',$member));
            $uid = $_ENV['db']->insertId();
            if (!$uid) {
                $_ENV['db']->rollback();
            }

            foreach($detail as $key=>$row) {
                if(empty($row)) unset($detail[$key]);
            }
            if (isset($detail['birthday'])) $detail['birthday'] = strtotime($detail['birthday']);
            $detail['uid'] = $uid;
            $_ENV['db']->runSql(getFastInsertSql('admincp_member_detail',$detail));
            
            $nodes = $_ENV['db']->fetchAll('SELECT * FROM `admincp_member_group_perm` WHERE `gid` = \''.$member['group_id'].'\'');
            foreach ((array)$nodes as $node) {
                $_ENV['db']->runSql("INSERT INTO `admincp_member_perm` ".$this->buildSql(array(
                        'uid' => $uid,
                        'node_id' => $node['node_id']
                    )));
            }

            $_ENV['db']->commit();

            $this->outputJson(1,'操作成功');
        }
        $this->view->groups = $_ENV['db']->fetchAll("SELECT * FROM `admincp_member_group`");
        $this->view->addScript('rili');
        $this->showMainPage('admincp/manager_modi');
    }

    public function modiModule() {
        if (AJAX) {
            $type = $_REQUEST['type'];

            if('fast' == $type) {
                $uid = (int)$_GET['wparam'];
                $field = $_GET['field'];
                $value = $_GET['value'];

                $_ENV['db']->runSql("UPDATE `admincp_member` SET `{$field}` = '{$value}' WHERE `uid` = '{$uid}'");
                $this->outputJson(1,'操作成功');
            } else if('activity' == $type) {
                $uid = (int)$_GET['uid'];

                $member = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `uid` = '{$uid}'");

                if (!$member) {
                    $this->outputJson(0,'用户不存在');
                }

                $activity = $member['activity'] == 1 ? '0' : '1';
                $_ENV['db']->runSql("UPDATE `admincp_member` SET `activity` = '{$activity}' WHERE `uid` = '{$uid}'");
                $this->outputJson(1,'操作成功','./res/image/'.($activity ? 'yes' : 'no').'.gif');
            } else if('resetpassword' == $type) {
                $uid = $_POST['uid'];
                $password = substr(uniqid(),7);
                $password_secret = md5($password);
                $_ENV['db']->runSql("UPDATE `admincp_member` SET `password` = '{$password_secret}' WHERE `uid` = '{$uid}'");
                $this->outputJson(1,'操作成功',$password);
            } else if('modi' == $type) {
                $cm = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `uid` = '{$_GET['uid']}'");
                if (!$cm) $this->outputJson(0,'指定的用户不存在');
                $fields = array('username','nickname','password','password_confirm','group_id');
                $member = getRequests($fields);

                foreach($fields as $key => $row) {
                    if(!$member[$row] && $member['password']!='') {
                        $this->outputJson(-1,'请补全必填信息',$row);
                    }
                }

                if($member['password'] && $member['password'] != $member['password_confirm']) {
                    $this->outputJson(-1,'请确认密码','password');
                }
                unset($member['password_confirm']);

                if (!$member['password']) {
                    unset($member['password']);
                } else {
                    $member['password'] = md5($member['password']);
                }

                if($member['group_id']!=$cm['group_id'] &&!$member['group_id'] || !$_ENV['db']->fetchCol("SELECT gid FROM `admincp_member_group` WHERE `gid` = '{$member['group_id']}'")) {
                    $this->outputJson(-1,'用户组选择错误','group_id');
                }

                $detail = getRequests(array('statutory_holiday','job','mobile','tel','tel','address','nplace','education','birthday','school'));

                if ($detail['mobile'] && (!is_numeric($detail['mobile']) || strlen($detail['mobile']) != 11)) {
                    $this->outputJson(-2,'手机号码必须是数字且为11位长度','mobile');
                }
				
				 if($detail['statutory_holiday'] && !preg_match('/^\d{0,3}$/',$detail['statutory_holiday'] )) 
				 {
                	$this->outputJson(-2,'法定假期必须是0~365之内的纯数字s','birthday');
				 }
				 if($detail['statutory_holiday'] && (int)$detail['statutory_holiday'] <0 || (int)$detail['statutory_holiday'] >365 ) {
					$this->outputJson(-2,'法定假期必须是0~365之内的纯数字','birthday');
				}
                
                $tel_length = strlen($detail['tel']);
                if ($tel_length && (!is_numeric($detail['tel']) || ($tel_length != 11 && $tel_length != 7))) {
                    $this->outputJson(-2,'座机号码只能为数字且长度为7或11位，区号和号码之间不用任何符号','tel');
                }

                if($detail['birthday'] && !strtotime($detail['birthday'])) {
                    $this->outputJson(-2,'生日格式错误，识别失败。','birthday');
                } else {
                    $detail['birthday'] = strtotime($detail['birthday']);
                }

                if ($cm['username']!=$member['username']) {
                    $member_row = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `username` = '{$member['username']}'");
                    if (!empty($member_row)) {
                        $this->outputJson(-1,'用户名已存在','username');
                    }
                }
                unset($member['username']);

                $_ENV['db']->runSql("UPDATE `admincp_member` ".$this->buildSql($member)." WHERE `uid` = '{$_GET['uid']}'");
                $_ENV['db']->runSql("UPDATE `admincp_member_detail` ".$this->buildSql($detail)." WHERE `uid` = '{$_GET['uid']}'");

                if($member['group_id']!=$cm['group_id']) {
                    $_ENV['db']->runSql("DELETE FROM `admincp_member_perm` WHERE `uid` = '{$_GET['uid']}'");
                    $nodes = $_ENV['db']->fetchAll('SELECT * FROM `admincp_member_group_perm` WHERE `gid` = \''.$member['group_id'].'\'');
                    foreach ((array)$nodes as $node) {
                        $_ENV['db']->runSql("INSERT INTO `admincp_member_perm` ".$this->buildSql(array(
                                'uid' => $_GET['uid'],
                                'node_id' => $node['node_id']
                            )));
                    }
                }
                $this->outputJson(1,'操作成功');
            }

            $this->outputJson(-403,'非法操作');
        }

        $member = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `uid` = '{$_GET['uid']}'");
        if (!$member) {
            $this->showMessage('指定的管理员不存在','back');
        }

        $this->view->member = $member;
        $this->view->memberd = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$_GET['uid']}'");
        $this->view->addScript('rili');
        $this->view->groups = $_ENV['db']->fetchAll("SELECT * FROM `admincp_member_group`");
        $this->showMainPage('admincp/manager_modi');
    }

    public function deleteModule() {
        if(AJAX) {
            $uid = (int)$_GET['uid'];
            $_ENV['db']->runSql("DELETE FROM `admincp_member` WHERE `uid` = '{$uid}'");
            $_ENV['db']->runSql("DELETE FROM `admincp_member_perm` WHERE `uid` = '{$uid}'");
            $_ENV['db']->runSql("DELETE FROM `admincp_member_detail` WHERE `uid` = '{$uid}'");
            $this->outputJson(1,'操作成功');
        } else {
            $this->showMessage('Bad request');
        }
    }

    public function permModule() {
        $uid = (int)$_REQUEST['uid'];
        $member = $_ENV['db']->fetch("SELECT * FROM `admincp_member` WHERE `uid` = '{$uid}'");
        if (!$member) $this->showmessage('用户不存在',-404);

        if(POST && AJAX) {
            $_ENV['db']->runSql("DELETE FROM `admincp_member_perm` WHERE `uid` = '{$uid}'");
            foreach((array)$_POST['node_ids'] as $node_id) {
                $_ENV['db']->runSql("INSERT INTO `admincp_member_perm` (`uid`,`node_id`) VALUES ('{$uid}','{$node_id}')");
            }

            $this->outputJson(1,'操作成功');
        }

        $rowset = $_ENV['db']->fetchAll("SELECT * FROM `admincp_member_perm` WHERE `uid` = '{$uid}'");
        $member_perm = array();
        foreach ((array)$rowset as $row) {
            $member_perm[] = $row['node_id'];
        }

        $node_rowset = $_ENV['db']->fetchAll("SELECT n.*,m.name as menu_name,m.menu_id FROM `admincp_node` as n LEFT JOIN `admincp_menu` as m ON n.menu_group_id = m.menu_id");

        $nodes = array();
        foreach ((array)$node_rowset as $node) {
            $node['checked'] = in_array($node['node_id'],$member_perm) ? 'checked' : '';
            $nodes[$node['menu_name']][] = $node;
        }
        ksort($nodes);
        
        $this->view->username = $member['username'];
        $this->view->nodes = $nodes;
        $this->showMainPage('admincp/manager_perm');
    }
}